package com.xin.ruanjian.omsystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xin.ruanjian.omsystem.R;
import com.xin.ruanjian.omsystem.adapter.OrderConfirmAdapter;
import com.xin.ruanjian.omsystem.app.MyApplication;
import com.xin.ruanjian.omsystem.bases.BaseActivity;
import com.xin.ruanjian.omsystem.bases.Login;
import com.xin.ruanjian.omsystem.bean.IndexBean.MsgBean.ShopBean;
import com.xin.ruanjian.omsystem.model.ShopCarModel;
import com.xin.ruanjian.omsystem.utils.HttpUtils;
import com.xin.ruanjian.omsystem.utils.ShopCarUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.xin.ruanjian.omsystem.bases.Contants.TS_POST_ORDER;

/**
 * 堂食订单确认界面
 */

public class TsConfirmOrderActivity extends BaseActivity {
    @BindView(R.id.tv_centerTitle)
    TextView tvCenterTitle;
    @BindView(R.id.iv_rightPic)
    ImageView ivRightPic;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_ts_order_detail_endprice)
    TextView tvTsOrderDetailEndprice;
    @BindView(R.id.tv_ts_order_detail_pay)
    TextView tvTsOrderDetailPay;
    @BindView(R.id.ll_ts_order_post)
    LinearLayout llTsOrderPost;
    @BindView(R.id.tv_ts_order_detail_name)
    TextView tvTsOrderDetailName;
    @BindView(R.id.tv_ts_order_detail_phone)
    TextView tvTsOrderDetailPhone;
    @BindView(R.id.tv_ts_order_detail_num)
    TextView tvTsOrderDetailNum;
    @BindView(R.id.tv_ts_order_detail_date)
    TextView tvTsOrderDetailDate;
    @BindView(R.id.ll_ts_order_seat_have)
    LinearLayout llTsOrderSeatHave;
    @BindView(R.id.ll_ts_order_seat_info)
    LinearLayout llTsOrderSeatInfo;
    @BindView(R.id.iv_tshop_icon)
    ImageView ivTshopIcon;
    @BindView(R.id.tv_tshop_name)
    TextView tvTshopName;
    @BindView(R.id.rv_tshop_dish_list)
    RecyclerView rvTshopDishList;
    @BindView(R.id.tv_all_count)
    TextView tvAllCount;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.ll_pay_type)
    LinearLayout llPayType;
    @BindView(R.id.tv_menu_request)
    EditText etMenuRequest;
    @BindView(R.id.tv_seat_request)
    EditText etSeatRequest;

    private OrderConfirmAdapter adapter;
    private List<ShopCarModel> shopCarData;
    private ShopBean shopBean;
    private Login login;
    private double allPrice;

    private String num, time, name, sex, phone, sRequest, dRequest;

    @Override
    protected void initContentView(Bundle bundle) {
        setContentView(R.layout.activity_ts_confirm_order);

    }

    @Override
    protected void initData() {
        login = MyApplication.getLogin();
        shopBean = (ShopBean) getIntent().getSerializableExtra("shop_info");
        num = getIntent().getStringExtra("table_num");
        time = getIntent().getStringExtra("table_time");
        name = getIntent().getStringExtra("user_name");
        sex = getIntent().getStringExtra("user_sex");
        phone = getIntent().getStringExtra("user_phone");
        sRequest = getIntent().getStringExtra("seat_request");
        dRequest = getIntent().getStringExtra("dish_request");
    }

    @Override
    protected void initView() {
        adapter = new OrderConfirmAdapter(context);
        rvTshopDishList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        rvTshopDishList.setAdapter(adapter);
        if (login != null) {
            shopCarData = ShopCarUtils.getShopCarData(shopBean.getShopid(), login.getUserId());
            adapter.setData(shopCarData);
            allPrice = ShopCarUtils.getShopCarAllPrice(shopCarData);
            tvTsOrderDetailEndprice.setText(getString(R.string.rmb) + allPrice);
            tvAllCount.setText(getString(R.string.rmb) + allPrice);
        } else {
            startActivity(new Intent(context, LoginActivity.class));
        }
    }

    @Override
    protected void initTitle() {
        showDefaultBackIcon();
        setTvCenterTitle("确认订单");
    }

    @Override
    protected void main() {
        tvTsOrderDetailName.setText(name + sex);
        tvTsOrderDetailPhone.setText(phone);
        tvTsOrderDetailNum.setText(num);
        tvTsOrderDetailDate.setText(time);
        if (!TextUtils.isEmpty(dRequest)) {
            etMenuRequest.setText(dRequest);
        }else {
            etMenuRequest.setText("无");
        }
        if (!TextUtils.isEmpty(sRequest)) {
            etSeatRequest.setText(sRequest);
        }else {
            etSeatRequest.setText("无");
        }
    }

    /**
     * 下单
     */
    private void postOrder() {
        showLoadingDialog();
        HttpUtils httpUtils = new HttpUtils(TS_POST_ORDER) {
            @Override
            public void onError(Call call, Exception e, int id) {
                showErrorDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                try {
                    JSONObject o = new JSONObject(response);
                    int state = o.getInt("state");
                    if (state == 1) {
                        Toast("下单成功！请尽快付款");
                        String orderid = o.getString("orderid");
                        startActivityForResult(new Intent(context, PaymentActivity.class)
                        .putExtra("orderid", orderid), 1200);
                    } else if (state == 0) {
                        showErrorDialog("服务器错误，请重新下单！");
                    } else if (state == 2) {
                        Toast("商品价格变动，请重新下单");
                    } else {
                        Toast(R.string.token_verification_fails_please_log_in_again);
                        MyApplication.saveLogin(null);
                        startActivity(new Intent(context, LoginActivity.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        if (login != null) {
            httpUtils.addParam("userid", login.getUserId() + "")
                    .addParams("token", login.getToken())
                    .addParams("shopid", shopBean.getShopid() + "")
                    .addParams("allprice", allPrice + "")
                    .addParams("name", name)
                    .addParams("sex", sex)
                    .addParams("time", time)
                    .addParams("phone", phone)
                    .addParams("num", num)
                    .addParams("seat_request", etSeatRequest.getText().toString())
                    .addParams("dish_request", etMenuRequest.getText().toString());
            JSONArray jsonArray = new JSONArray();
            for (ShopCarModel model : ShopCarUtils.getShopCarData(shopBean.getShopid(), login.getUserId())) {
                JSONObject object = new JSONObject();
                try {
                    object.put("mid", model.getMid()).put("did", model.getDid())
                            .put("dname", model.getdName()).put("dprice", model.getdPrice())
                            .put("dpic", model.getdPic()).put("num", model.getdNum());
                    jsonArray.put(object);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            httpUtils.addParam("order_info", jsonArray.toString());
            httpUtils.clicent();
        } else {
            startActivity(new Intent(context, LoginActivity.class));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.tv_ts_order_detail_pay, R.id.ll_pay_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ts_order_detail_pay:
                postOrder();
                break;
            case R.id.ll_pay_type:
                //前往选择界面
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1200 && resultCode == 1201) {
            setResult(1101);
            finish();
        }
    }

}
